<template>
	<div>
		<!-- 头部 -->
		<a-form ref="searchRef" :rules="rules" :model="searchForm" :hideRequiredMark="true" style="margin-bottom: 20px">
			<a-row>
				<a-col :span="8">
					<a-form-item name="saleValue" label="销售状态">
						<a-row>
							<a-col :span="8" v-for="(item, index) in saleStatusOptions" :key="item.id"
								:class="index == statusAct ? 'act-font-color' : ''"
								@click="chooseStatus(item.id, index)">{{ item.name }}</a-col>
						</a-row>
					</a-form-item>
				</a-col>
				<!-- <a-col :span="4" :offset="1">
          <a-form-item name="saleValue" label="耗材名称">
            <a-input placeholder="请输入耗材名称"></a-input>
            <a-input-group compact>
              <a-select
                ref="select"
                v-model:value="searchForm.saleValue"
                @focus="focus"
                @change="handleChange"
                placeholder="请选择"
              >
                <a-select-option
                  v-for="item in consumeOptions"
                  :value="item.name"
                  :key="item.id"
                  >{{ item.name }}</a-select-option
                >
              </a-select>
              <a-input
                v-model:value="searchForm.inputValue"
                style="width: 50%"
              />
            </a-input-group>
          </a-form-item>
        </a-col> -->
				<a-col :span="6" :offset="1">
					<a-form-item name="saleValue" label="关键字">
						<a-input placeholder="请输入关键字" v-model:value="searchForm.keyword"></a-input>
					</a-form-item>
				</a-col>
				<a-col :span="4" :offset="1">
					<a-button type="primary" @click="search" class="d-a-center">搜索</a-button></a-col>
			</a-row>
		</a-form>

		<!-- 列表 -->
		<a-table :columns="columns" :row-selection="rowSelection" :data-source="list" bordered :loading="loading"
			:pagination="pagination" @change="handleTableChange">
			<template #title><a-button type="primary" @click="add" v-has="{ a: $route, b: 2 }"
					class="d-a-center">新增</a-button></template>
			<template #consumables="{ record }">
				<div>
					{{ record.consumables[0].bleName }}
				</div>
			</template>
			<template #classify="{ record }">
				<div v-if="record.serviceId">
					{{ record.serviceId }}
				</div>
			</template>
			<template #stack="{ record, index }">
				<div v-has="{ a: $route, b: 2 }" @click="changeStack(record.status, index, record.id)">
					<a-switch v-model:checked="record.status" :checkedValue="0" :unCheckedValue="1" />
				</div>
			</template>
			<template #operation="{ record }">
				<a-button type="link" @click="edit(record)" v-has="{ a: $route, b: 2 }">编辑</a-button>
				<a-button type="link" danger @click="del(record.key)" v-has="{ a: $route, b: 2 }">删除</a-button>
			</template>
		</a-table>
		<!-- 多项删除 -->
		<a-button type="danger" @click="listDel" v-has="{ a: $route, b: 2 }">删除</a-button>

		<div>
			<!-- 弹窗 -->
			<a-modal v-if="visible" width="60%" wrap-class-name="full-modal" :visible="visible" :title="modalTitle"
				okText="保存" @ok="save" @cancel="cancel" :destroyOnClose="true">
				<a-form ref="formRef" :rules="rules1" :model="form" :hideRequiredMark="true" :label-col="labelCol"
					:wrapper-col="wrapperCol">
					<a-form-item label="耗材包名称" name="name">
						<a-input v-model:value="form.name" placeholder="请输入耗材包名称"></a-input>
					</a-form-item>
					<a-form-item label="分类">
						<a-cascader v-model:value="value" :options="typeList" :load-data="loadData" change-on-select
							:field-names="{
                label: 'name',
                value: 'id',
              }" />
					</a-form-item>

					<a-form-item label="耗材包描述/明细" name="consumables">
						<a-select ref="select" mode="multiple" v-model:value="consumables" @focus="focus"
							@change="selectConsume" placeholder="请选择耗材包明细">
							<!-- 一绑定item就会报错 -->
							<a-select-option v-for="item in detaiList" :value="item.id"
								:key="item.id">{{ item.bleName }}</a-select-option>
						</a-select>
					</a-form-item>
					<a-form-item label="耗材包编号" name="bagNumber">
						<a-input v-model:value="form.bagNumber" placeholder="请输入耗材包编号名称的首字母大写"></a-input>
					</a-form-item>
					<a-form-item label="销售状态">
						<a-radio-group v-model:value="form.isDele">
							<a-radio :value="0">上架</a-radio>
							<a-radio :value="1">下架</a-radio>
						</a-radio-group>
					</a-form-item>
					<a-form-item label="市场价" name="bazaarPrice">
						<a-input v-model:value="form.bazaarPrice" placeholder="请输入耗材包市场价"></a-input>
					</a-form-item>
					<a-form-item label="销售价" name="sellPrice">
						<a-input v-model:value="form.sellPrice" placeholder="请输入耗材包销售价"></a-input>
					</a-form-item>
				</a-form>
				<!-- <a-input placeholder="请输入分类名称" v-model:value="title" @pressEnter="save"></a-input> -->
			</a-modal>
		</div>
	</div>
</template>
<script>
	import {
		reactive,
		ref,
		computed,
		createVNode,
		watch,
		toRefs,
		unref,
		toRaw,
		isReactive,
		toRef,
	} from "vue";
	import {
		CheckOutlined,
		EditOutlined,
		ExclamationCircleOutlined,
		QuestionCircleOutlined,
	} from "@ant-design/icons-vue";
	import {
		Modal,
		message
	} from "ant-design-vue";
	import {
		selectAllConsumableBag,
		upOrDownConsumableBag,
		selectAllDetail,
		updateAndAddConsumableBag,
		deleteConsumableBag,
	} from "@/api/consume/index.js";
	import {
		selectAllService,
		selectAllType
	} from "@/api/service/index.js";
	import { useModal } from "@/hooks"
	import {
		deleteObjBlank
	} from "@/assets/js/common.js";
	import * as api from "@/api/service/index.js";
	export default {
		setup() {
			const searchRef = ref("");
			const formRef = ref("");

			const data = reactive({
				list: [],
				loading: true,
				visible: false,
				serviceList: [], //分类列表
				detaiList: [],
				consumables: [], //默认绑定ID即可
				statusAct: 0,
				searchForm: {},
				typeList: [],
				form: {
					isDele: 0
				},
				value: [], //分类-这个远程加载的数据好像不可以哎
				defaultValue: [],
			});

			const title = ref(""); //分类名称

			const modalTitle = ref("新增耗材");
			const rules = {
				//  portValue: [{ required: true, message: '请选择端口!', trigger: 'change'}],
				//  inputValue: [{ required: true, message: '请输入搜索内容!', trigger: 'blur'}],
			};
			const rules1 = {
				name: [{
					required: true,
					message: "请输入耗材名称!"
				}],
				sellPrice: [{
					required: true,
					message: "请输入销售价!"
				}],
				serviceId: [{
					required: true,
					message: "请输入服务类型!"
				}],
				typeId: [{
					required: true,
					message: "请输入服务分类!"
				}],
				bazaarPrice: [{
					required: true,
					message: "请输入市场价格!"
				}],
				bagNumber: [{
					required: true,
					message: "请输入耗材编号!"
				}],
				// value: [{ required: true, message: "请选择耗材分类!" }],
			};

			// 分页器
			const page = reactive({
				current: 1,
				pageSize: 10,
				total: 0,
			});

			const saleStatusOptions = reactive([{
					name: "全部",
					id: "",
				},
				{
					name: "上架",
					id: 0,
				},
				{
					name: "下架",
					id: 1,
				},
			]);
			const consumeOptions = reactive([{
					name: "耗材名称",
					id: 1,
				},
				{
					name: "耗材分类",
					id: 1,
				},
			]);
			const delListId = ref([]); //删除数组ID集合
			const chooseStatus = (status, index) => {
				data.statusAct = index;
				data.searchForm.status = status;
				page.current = 1;
				init();
			};
			// 查询
			const search = () => {
				page.current = 1;
				init();
			};
			const columns = [{
					title: "耗材编号",
					dataIndex: "id",
					className: "table",
				},
				{
					title: "耗材包名称",
					dataIndex: "name",
					className: "table",
				},
				{
					title: "耗材明细",
					dataIndex: "consumables",
					className: "table",
					slots: {
						customRender: "consumables",
					},
				},
				{
					title: "市场价",
					dataIndex: "bazaarPrice",
					className: "table",
				},
				{
					title: "销售价",
					dataIndex: "sellPrice",
					className: "table",
				},
				{
					title: "分类",
					dataIndex: "serviceId",
					// dataIndex: "serveName",
					className: "table",
					slots: {
						customRender: "classify",
					},
				},
				{
					title: "是否上架",
					dataIndex: "status",
					className: "table",
					slots: {
						customRender: "stack",
					},
				},
				{
					title: "操作",
					dataIndex: "operation",
					className: "table",
					slots: {
						customRender: "operation",
					},
				},
			];

			// 分页器
			const pagination = computed(() => ({
				current: page.current,
				pageSize: page.pageSize,
				pageSizeOptions: ["10", "20", "30"],
				showTotal: (total, range) => {
					return "共" + total + "条";
				},
				total: page.total,
				showQuickJumper: true,
				showSizeChanger: true,
			}));

			// 分页器改变的时候
			const handleTableChange = (pagination, filters, sorter) => {
				console.log(pagination, "当前分页");
				page.current = pagination.current;
				page.pageSize = pagination.pageSize;

				// 请求列表接口
				init();
			};
			const cancel = () => {
				data.visible = false;
				title.value = "";
				data.form = {};
				data.consumables = [];
			};
			// 新增
			const add = () => {
				console.log(
					data.typeList,
					"data.typeListdata.typeListdata.typeListdata.typeList"
				);
				data.visible = true;
			};
			const edit = async (item) => {
				data.visible = true;
				await initFirstServiceList();
				// item.typeId = String(item.typeId);
				console.log(item, "item");
				data.form = item;
				data.consumables = item.consumables.map((el) => el.id);
				modalTitle.value = "编辑耗材";

				// 二级
				if (true) {
					let obj = {
						parentId: item.typeId,
					};
					let res = await selectAllType(obj);
					if (res.success) {
						let index = data.typeList.findIndex((el) => el.id == item.typeId);
						console.log(index, "查找到的index是-----");
						data.typeList[index].children = res.object;
						data.typeList = [...data.typeList];
						// data.typeList[index].children = res.object;
						console.log(data.typeList);
						if (true) {
							// 三级
							let obj1 = {
								pageNum: 1,
								pageSize: 100,
								typeId: data.value[1],
							};
							let res2 = await selectAllService(obj1);
							if (res2.success) {
								let index1 = res.object.findIndex((el) => el.id == data.value[1]);
								res2.object.records.map((el) => (el.name = el.serveName));
								// debugger;
								data.typeList[index].children.map((m) => {
									m.children = res2.object.records;
									return m;
								});

								data.typeList = [...data.typeList];
							}
						}
					}
				}

				// 二级分类
				// let obj = item;
				// item.id = obj.typeId;
				// loadData([item]);
				let obj = {
					pageNum: 1,
					pageSize: 80,
					typeId: item.typeId,
				};
				// let res = await selectAllService(obj);
				// if (res.success) {
				//   let index = data.typeList.findIndex((el) => el.id == item.typeId);
				//   console.log(index, "查找到的index是-----");
				//   res.object.records.map((el) => (el.name = el.serveName));
				//   data.typeList[index].children = res.object.records;

				//   data.typeList = [...data.typeList];
				// }
				// data.value[2] = item.serviceId;

				console.log(data.value, "默认选中的是");
				data.value[0] = Number(item.typeId);
				data.value[1] = String(item.secondTypeId);
				data.value[2] = item.serviceId;
				data.visible = true;
			};
			const Typename = (id) => {
				let item = data.typeList.find((el) => el.id == id);
				console.log(item, "分类名字是");
				return item;
			};

			const serviceName = (id) => {
				let list = data.serviceList.find((el) => el.id == id);
				if (list.serviceName) {
					// return list.serveName;
					return list;
				}
			};
			const save = () => {
				if (data.value.length != 3) {
					message.error("请选择具体服务");
					return;
				}
				data.form.typeId = data.value[0];
				data.form.secondTypeId = data.value[1];
				data.form.serviceId = data.value[2];
				console.log(data.form, "表单内容是");

				formRef.value.validate().then(async () => {
					let arr = [];
					// 查找耗材包明细内容两个数组比较
					data.detaiList.forEach((el) => {
						data.consumables.forEach((item) => {
							if (item == el.id) {
								arr.push(el);
							}
						});
					});
					if (data.value.length == 0) {
						message.error("请选择耗材分类!!!");
						return;
					}

					data.form.consumables = arr;
					let res = await updateAndAddConsumableBag(data.form);
					if (res.success) {
						init();
						message.success("新增成功");
						data.visible = false;
					}
				});
			};
			// 删除
			const del = (key) => {
				const {closeModal} = useModal.confirm({
					title: () => "你确定删除当前项吗?",
					icon: () => createVNode(QuestionCircleOutlined),
					content: () =>
						createVNode(
							"div", {
								style: "color:red;",
							},
							"删除当前数据后不可恢复，请谨慎考虑。"
						),
					onOk: async () => {
						let res = await deleteConsumableBag([Number(key)]);
						if (res.success) {
							message.success("删除成功");
							init();
							closeModal()
						}
					},

					class: "test",
				});
			};
			const selectConsume = (e) => {
				console.log(e);
			};
			const selectService = (e) => {
				// console.log(e, "服务类型");s
			};
			const selectType = (e) => {};

			// 全选反选
			const rowSelection = ref({
				checkStrictly: false,
				onChange: (selectedRowKeys, selectedRows) => {
					console.log(
						`selectedRowKeys: ${selectedRowKeys}`,
						"selectedRows: ",
						selectedRows
					);
					delListId.value = selectedRowKeys;
				},
				onSelect: (record, selected, selectedRows) => {
					//console.log(record, selected, selectedRows,'选择多项');
				},
				onSelectAll: (selected, selectedRows, changeRows) => {
					//console.log(selected, selectedRows, changeRows,'全选操作');
					// 数组项
				},
			});
			// 删除多项
			const listDel = () => {
				const {closeModal} = useModal.confirm({
					title: "确定删除所选内容项吗?",
					icon: createVNode(ExclamationCircleOutlined),
					content: "删除后将不可恢复，请谨慎操作。",
					okText: "确定",
					okType: "danger",
					cancelText: "取消",
					onOk: async () => {
						console.log(delListId.value);
						let data = delListId.value.map((el) => (el = Number(el)));

						let res = await deleteConsumableBag(data);
						if (res.success) {
							message.success("删除成功");
							init();
							closeModal()
						}
					},
					
				});
			};

			// 是否上下架 就把原来的状态改变下就行，传递下当前项的耗材ID即可，
			const changeStack = (checked, index, id) => {
				console.log(page.pageNum);
				console.log(checked, index, "是否上下架");
				let title = checked == 0 ? "上架" : "下架";
				// 弹框提示？确定上下架吗
				const {closeModal} = useModal.confirm({
					title: () => `确定${title}当前耗材包吗?`,
					icon: () => createVNode(ExclamationCircleOutlined),
					onOk: async () => {
						let res = await upOrDownConsumableBag(id);
						if (res.success) {
							data.list[index].status = Number(checked);
							init();
							closeModal()
						}
					},
					onCancel() {
						let flag = checked == 0 ? 1 : 0;
						data.list[index].status = flag;
						closeModal()
					},
					class: "test",
				});
			};
			initFirstServiceList();

			init();
			initAllDetailList();
			async function init() {
				let obj = {
					pageNum: page.current,
					pageSize: page.pageSize,
					...data.searchForm,
				};
				let res = await selectAllConsumableBag(obj);
				if (res.success) {
					res.object.list.map((el) => (el.key = el.id));
					data.list = res.object.list;
					// data.list.forEach(el=>{
					// })
					data.loading = false;
					page.total = res.object.total;
				}
			}
			// 一级分类
			async function initFirstServiceList() {
				api.queryserviceTypeParent().then((r) => {
					r.object.map((m) => (m.name = m.kindName));
					r.object.map((el) => (el.isLeaf = false));
					data.typeList = [...r.object];
					// initServiceList(data.tabs[0].id)
				});
			}
			async function initServiceList(pid) {
				let obj = {
					parentId: pid,
				};
				let res1 = await selectAllType(obj);
				if (res1.success) {
					res1.object.map((el) => (el.isLeaf = false)); //id是string类型的
					data.typeList = res1.object;
				}
			}
			async function initAllDetailList() {
				let res = await selectAllDetail();
				if (res.success) {
					data.detaiList = res.object;
				}
			}

			const loadData = async (selectedOptions) => {
				console.log("点击了选择", selectedOptions);

				const targetOption = selectedOptions[selectedOptions.length - 1];
				targetOption.loading = true; // load options lazily
				// 二级
				if (selectedOptions.length == 1) {
					let obj = {
						parentId: targetOption.id,
					};
					let res1 = await selectAllType(obj);
					if (res1.success) {
						res1.object.map((el) => (el.isLeaf = false)); //id是string类型的
						targetOption.children = res1.object;
						data.typeList = [...data.typeList];
					}
				} else {
					// 三级
					let obj = {
						pageNum: 1,
						pageSize: 200,
						typeId: targetOption.id,
					};
					let res2 = await selectAllService(obj);
					if (res2.success) {
						res2.object.records.map((el) => (el.name = el.serveName));
						targetOption.children = res2.object.records;
						data.typeList = [...data.typeList];
					}
				}

				// let obj = {
				//   pageNum: 1,
				//   pageSize: 80,
				//   typeId: selectedOptions[0].id,
				// };
				// let res = await selectAllService(obj);
				// if (res.success) {
				//   targetOption.loading = false;
				//   res.object.records.map((el) => (el.name = el.serveName));
				//   targetOption.children = res.object.records;

				//   data.typeList = [...data.typeList];
				// }
			};
			return {
				...toRefs(data),
				saleStatusOptions,
				consumeOptions,
				searchRef,
				modalTitle,
				formRef,
				rules,
				rules1,
				columns,
				pagination,
				title,
				labelCol: {
					style: {
						width: "150px"
					}
				},
				wrapperCol: {
					span: 14
				},
				handleTableChange,
				search,
				add,
				del,
				save,
				cancel,
				edit,
				rowSelection,
				listDel,
				changeStack,
				serviceName,
				selectConsume,
				selectService,
				chooseStatus,
				Typename,
				selectType,
				loadData,
			};
		},

		components: {
			CheckOutlined,
			EditOutlined,
			ExclamationCircleOutlined,
			QuestionCircleOutlined,
		},
	};
</script>

<style scoped lang="less">
	.act {
		color: #2a9d8f;
	}
</style>